<?php

namespace Omnisend\Omnisend\Model\EntityDataSender;

use Magento\Sales\Api\Data\OrderInterface;
use Omnisend\Omnisend\Model\Api\Request\RequestInterface;
use Omnisend\Omnisend\Model\Attribute\IsImported\ImportStatus;

class Order implements EntityDataSenderInterface
{
    /**
     * @var RequestInterface
     */
    protected $orderRequest;

    /**
     * @var ImportStatus
     */
    protected $importStatus;

    /**
     * @param RequestInterface $orderRequest
     * @param ImportStatus $importStatus
     */
    public function __construct(RequestInterface $orderRequest, ImportStatus $importStatus)
    {
        $this->orderRequest = $orderRequest;
        $this->importStatus = $importStatus;
    }

    /**
     * @param OrderInterface $order
     * @return null|string
     */
    public function send($order)
    {
        $postStatus = $order->getOmnisendPostStatus();

        if ($postStatus) {
            return $this->putFirst($order);
        }

        return $this->postFirst($order);
    }

    /**
     * @param OrderInterface $order
     * @return null|string
     */
    protected function postFirst($order)
    {
        $response = $this->orderRequest->post($order, $order->getStoreId());

        if (!$this->importStatus->getImportStatus($response)) {
            return $this->orderRequest->put($order->getEntityId(), $order, $order->getStoreId());
        }

        return $response;
    }

    /**
     * @param OrderInterface $order
     * @return null|string
     */
    protected function putFirst($order)
    {
        $response = $this->orderRequest->put($order->getEntityId(), $order, $order->getStoreId());

        if (!$this->importStatus->getImportStatus($response)) {
            return $this->orderRequest->post($order, $order->getStoreId());
        }

        return $response;
    }
}
